package com.zy.dingdong.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zy.dingdong.R;
import com.zy.dingdong.adapter.MsgAdapter;
import com.zy.dingdong.entity.Friend;
import com.zy.dingdong.entity.Message;
import com.zy.dingdong.entity.MessageItemView;
import com.zy.dingdong.service.FriendService;
import com.zy.dingdong.service.MessageService;
import com.zy.dingdong.util.OkHttpUtil;
import com.zy.dingdong.util.PictureUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ChatActivity extends BaseActivity {

    private EditText inputMessage;

    private TextView titleText;

    private RecyclerView msgRecView;

    private MsgAdapter adapter;

    private Friend currentFriend;
    public int friendNetId;
    private ArrayList<Message> messageList;
    private MessageItemView msgItemView;

    private FriendService friendService;
    private MessageService messageService;

    public ImageView hasNewMsgView;

    /****/
    private ImageView sendImage;
    /****/
    private PictureUtil pictureUtil;


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat);
        friendService = new FriendService();
        messageService = new MessageService();

        //聊天记录数据初始化
        //将聊天记录查出，创建MessageItemView对象,用于给适配器传参
        initData();
        //渲染非列表界面
        titleText = findViewById(R.id.title_text);
        inputMessage = findViewById(R.id.input_message);

        msgRecView = findViewById(R.id.msg_recycle_view);
        titleText.setText(currentFriend.getName());

        hasNewMsgView = findViewById(R.id.has_new_message);
        hasNewMsgView.setVisibility(View.GONE);
        /****/
        //添加
        sendImage = findViewById(R.id.send_image);
        pictureUtil = new PictureUtil(ChatActivity.this);
        /****/

        LinearLayoutManager layoutManager=new LinearLayoutManager(this);

        msgRecView.setLayoutManager(layoutManager);

        adapter = new MsgAdapter(ChatActivity.this,msgItemView);

        msgRecView.setAdapter(adapter);
        //消息列表定位到最近的一条消息
        msgRecView.scrollToPosition(messageList.size()-1);
        //使用软键盘监听发送
        inputMessage.setImeOptions(EditorInfo.IME_ACTION_SEND);
        inputMessage.setInputType(EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE);
        inputMessage.setMaxLines(2);
        inputMessage.setSingleLine(false);
        inputMessage.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND
                        || actionId == EditorInfo.IME_ACTION_DONE
                        || (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
                        String content = inputMessage.getText().toString();
                        if (!content.equals("")){
                          //此处应该先发送消息，成功则存储到本地
                            Message message = new Message(owner.getNetId(),currentFriend.getNetId(),content);
                            Date currentTime = new Date(System.currentTimeMillis());
                            message.setCreateTime(currentTime.getTime());
                            //消息类型为文本消息
                            message.setMessageType(1);
                            //添加数据
                            addMsg(message,true);
                            message.setRead(false);
                            inputMessage.setText("");
                            //发送数据
                            wsClient.send(JSON.toJSONString(message));
                        }
                }
                return false;
            }
        });
        /****/
        //监听sendImage点击
        sendImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String[] getPictureWays = new String[]{"相册", "相机"};
                AlertDialog dialog = new AlertDialog.Builder(ChatActivity.this)
                        .setItems(getPictureWays, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int i) {
                                switch (i) {
                                    case 0:
                                        pictureUtil.openPictureLib();
                                        break;
                                    case 1:
                                        pictureUtil.openCamera();
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }).create();
                dialog.show();
            }
        });
        /****/
    }

    private void initData() {
        //从intent中取出currentNetId并查出对象
        Intent intent = getIntent();
        friendNetId = intent.getIntExtra("friendNetId",-1);
        currentFriend = friendService.findByNetId(friendNetId,owner.getNetId());
        if (currentFriend == null){
            Toast.makeText(ChatActivity.this,"对方不是您的好友",Toast.LENGTH_SHORT);
            //如果不是好友则退出该活动
        }
        //从数据库中查找聊天记录-默认最近20条记录
        messageList = messageService.findNearlyMessage(friendNetId,owner.getNetId());
        //组装成MessageItemViw
        msgItemView = new MessageItemView(currentFriend,owner,messageList);
    }
    //消息添加方法
    public void addMsg(Message message,boolean isRead){
        msgItemView.messages.add(message);
        adapter.notifyItemInserted(messageList.size()-1);
        msgRecView.scrollToPosition(messageList.size()-1);
        message.setRead(isRead);
        //消息存储到本地
        message.save();
    }

    /****/
    //添加图片获取回调
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        File pictureFile = null;
        switch (requestCode) {
            //图片请求来自于相机
            case PictureUtil.FROM_CAMERA:
                if (resultCode == RESULT_OK) {
                        pictureFile = pictureUtil.getPictureFile();
                }
                break;
            //图片请求来自于相册
            case PictureUtil.FROM_PICTURE_LIB:
                if (resultCode == RESULT_OK) {
                    String path = pictureUtil.getRealPathFromUri(ChatActivity.this, data.getData());
                    pictureFile = new File(path);
                }
                break;
            default:
                break;
        }
        //构建参数map并调用发送图片请求
        if (pictureFile != null){
            Map params=new HashMap();
            params.put("senderId",owner.getNetId());
            params.put("receiverId",friendNetId);
            System.out.println("上传的图片名称为：" + pictureFile.getName());
            sendImageRequest(params,pictureFile);
        }
    }
    //发送图片请求与响应。上传图片,处理图片路径
    private void sendImageRequest(final Map paramMap, final File file){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String url = SERVER_URL+"/message/imageUpload";
                    String jsonStr = OkHttpUtil.fileUpload(url, file, paramMap);
                    sendImageResponse(jsonStr);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void sendImageResponse(final String jsonStr){
        ChatActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Map jsonMap = JSON.parseObject(jsonStr);
                final String message = (String) jsonMap.get("message");
                if (message.equals("success")){
                    Toast.makeText(ChatActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                    //上传成功之后构建图片文件消息，再进行消息发送及存储
                    JSONObject responseData = (JSONObject) jsonMap.get("data");
                    String content = (String)responseData.get("fileName");
                    Message sendMsg = new Message(owner.getNetId(),currentFriend.getNetId(),content);
                    Date currentTime = new Date(System.currentTimeMillis());
                    sendMsg.setCreateTime(currentTime.getTime());
                    //设置消息类型为2，即图片类型
                    sendMsg.setMessageType(2);
                    addMsg(sendMsg,true);
                    //消息设置为未读
                    sendMsg.setRead(false);
                    //发送消息
                    wsClient.send(JSON.toJSONString(sendMsg));
                }else{
                    Toast.makeText(ChatActivity.this, message, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    //请求权限的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //申请相机权限
        if (requestCode == PictureUtil.CAPTURE_PERMISSION){
            if (grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                //执行拍照
                pictureUtil.doTake();
            } else{
                Toast.makeText(this,"你没有获得相机的权限",Toast.LENGTH_SHORT).show();
            }
        }
        //申请读取内存的权限
        else if (requestCode == PictureUtil.PICTURE_LIB_PERMISSION){
            if (grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                //执行从相册选取图片
                pictureUtil.openAlbum();
            } else{
                Toast.makeText(this,"你没有获得访问相册的权限",Toast.LENGTH_SHORT).show();
            }
        }
    }
}
